layui.use(['layer', 'form', 'table', 'upload', "laydate", 'tableSelect'], function () {
    var layer = layui.layer
        , form = layui.form
        , $ = layui.$
        , table = layui.table
        , upload = layui.upload
        , laydate = layui.laydate
        , tableSelect = layui.tableSelect

    laydate.render({
        elem: ".start",
        done: function (value, date, enddate) {
            Sum(false)
            Sum(true)

        }
    });

    //新增证券下拉表单
    tableSelect.render({
        elem: 'input[name="securityName"]'
        , table: {
            url: './TestSelectSecurity'
            , cellMinWidth: 60
            , cols: [
                [
                    {type: 'checkbox'},
                    {field: 'securityId', title: '证券ID'},
                    {field: 'securityName', title: '证券名称'},
                ]
            ]
        }
        , done: function (elem, data) {
            var count = data.data.length;
            if (count > 1) {
                layer.msg('不能选择多条证券!', {icon: 2, time: 1000, shade: [0.5, '#000', true]});
            } else if (count == 0) {
                layer.msg('请选择证券!', {icon: 2, time: 1000, shade: [0.5, '#000', true]});
            } else {
                $("input[name='securityName']").val(data.data[0].securityName);
                $("input[name='securityId']").val(data.data[0].securityId);
                $.post("./ExchangeRateMoney", {securityId: data.data[0].securityId}, function (msg) {
                    $("#stampDuty").val(msg.stampDuty);
                    $("#transferFee").val(msg.transferFee)
                    $("#control").val(msg.collectionFee)
                    $("#handle").val(msg.handlingFee)

                })
            }
        }
    })
    //新增现金下拉表单
    tableSelect.render({
        elem: 'input[name="accountName"]'
        , table: {
            url: './selectCashOne'
            , cellMinWidth: 60
            , cols: [
                [
                    {type: 'checkbox'},
                    {field: 'cashId', title: '现金账户ID'},
                    {field: 'accountName', title: '账户名称'},
                ]
            ]
        }
        , done: function (elem, data) {
            var count = data.data.length;
            if (count > 1) {
                layer.msg('不能选择多条现金账户!', {icon: 2, time: 1000, shade: [0.5, '#000', true]});
            } else if (count == 0) {
                layer.msg('请选择现金账户!', {icon: 2, time: 1000, shade: [0.5, '#000', true]});
            } else {
                $("input[name='accountName']").val(data.data[0].accountName);
                $("input[name='cashId']").val(data.data[0].cashId)
            }
        }
    })
    //新增券商下拉表单
    tableSelect.render({
        elem: 'input[name="brokerName"]'
        , table: {
            url: './TestSelectBroker'
            , cellMinWidth: 60
            , cols: [
                [
                    {type: 'checkbox'},
                    {field: 'brokerId', title: '券商ID'},
                    {field: 'brokerName', title: '券商名称'},
                ]
            ]
        }
        , done: function (elem, data) {
            var count = data.data.length;
            if (count > 1) {
                layer.msg('不能选择多条券商!', {icon: 2, time: 1000, shade: [0.5, '#000', true]});
            } else if (count == 0) {
                layer.msg('请选择券商!', {icon: 2, time: 1000, shade: [0.5, '#000', true]});
            } else {
                $("input[name='brokerName']").val(data.data[0].brokerName);
                $("input[name='brokerId']").val(data.data[0].brokerId)
            }
        }
    })
    //新增交易席位下拉表单
    tableSelect.render({
        elem: 'input[name="seatName"]'
        , table: {
            url: './TestSelectDealData'
            , cellMinWidth: 60
            , cols: [
                [
                    {type: 'checkbox'},
                    {field: 'seatId', title: '席位ID'},
                    {field: 'seatName', title: '席位名称'},
                    {field: 'commission', hide: true},
                ]
            ]
        }
        , done: function (elem, data) {
            var count = data.data.length;
            if (count > 1) {
                layer.msg('不能选择多条席位!', {icon: 2, time: 1000, shade: [0.5, '#000', true]});
            } else if (count == 0) {
                layer.msg('请选择席位!', {icon: 2, time: 1000, shade: [0.5, '#000', true]});
            } else {
                $("input[name='seatName']").val(data.data[0].seatName);
                $("input[name='seatId']").val(data.data[0].seatId)
                $("input[name='money']").val(data.data[0].commission)
            }
        }
    })


    table.render({
        elem: '#dealDate'//表格的ID
        , url: './selectDealDate'//表格的数据源 controller里的方法
        , cellMinWidth: 60 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
        , height: 'full-180'
        , toolbar: '#userToolBar'//通过工具条的ID来区分
        , page: true//开启分页
        , limit: 5//默认进去每页显示5条
        , limits: [5, 10, 15]//自己设置下拉列表5,10,15，行
        , methods: "post"// 请求方式
        , cols: [[{type: 'checkbox', fixed: 'left'}
            , {field: 'dealId', title: '交易id', width: 130, align: 'center', hide: true}
            , {field: 'money', title: '费率', width: 130, align: 'center', hide: true}
            , {field: 'dealTime', title: '交易日期', width: 130, align: 'center'}
            , {field: 'accountName', title: ' 现金账户', width: 200, align: 'center'}
            , {field: 'securityName', title: ' 证券名称', width: 200, align: 'center'}
            , {field: 'brokerName', title: '券商名称', width: 130, align: 'center'}
            , {field: 'dealNumber', title: '交易数量', width: 130, align: 'center'}
            , {field: 'dealPrice', title: '交易单价', width: 130, align: 'center'}
            , {field: 'endMoney', title: '结算金额', width: 130, align: 'center'}
            , {field: 'dealMoney', title: '交易金额', width: 130, align: 'center'}
            , {field: 'endTime', title: '结算日期', width: 130, align: 'center'}
            , {field: 'cashId', title: '现金账户ID', width: 130, align: 'center', hide: true}
            , {field: 'fundId', title: '基金代码', width: 130, align: 'center', hide: true}
            , {field: 'securityId', title: '证券ID', width: 130, align: 'center', hide: true}
            , {field: 'brokerId', title: '券商ID', width: 130, align: 'center', hide: true}
            , {field: 'seatId', title: '席位ID', width: 130, align: 'center', hide: true}
            , {field: 'seatName', title: '席位名称', width: 130, align: 'center', hide: true}
            , {field: 'commission', title: '佣金费用', width: 130, align: 'center', hide: true}
            , {field: 'transferFee', title: '过户费', width: 130, align: 'center', hide: true}
            , {field: 'handlingFee', title: '经手费', width: 130, align: 'center', hide: true}
            , {field: 'stampDuty', title: '印花税', width: 130, align: 'center', hide: true}
            , {field: 'collectionFee', title: '征管费', width: 130, align: 'center', hide: true}
            , {field: 'security', title: '证券利息', width: 130, align: 'center', hide: true}
            , {
                field: 'dealWay', title: '交易方式', width: 130, align: 'center', templet: function (item) {
                    var dealWay = item.dealWay;
                    if (dealWay == 1) {
                        return "买入"
                    } else if (dealWay == 2) {
                        return "卖出"
                    } else if (dealWay == 3) {
                        return "分红"
                    } else if (dealWay == 4) {
                        return "送股"
                    }
                }
            }
            , {
                field: 'dealState', title: '交易状态', width: 130, align: 'center', templet: function (item) {
                    if (item.dealState == 0) {
                        return "<span style='color: green'>未结算</span>";
                    } else {
                        return "<span style='color: red'>已结算</span>";
                    }
                }
            }
            , {fixed: 'right', field: 'operation', title: '操作', width: 160, align: 'center', toolbar: '#toolEventDemo'}
        ]],
        //返回参数取名字
        request: {
            pageName: 'page',   // 页码的参数名称，默认：page
            limitName: 'row',  // 每页数据量的参数名，默认：limit
        }
    });

    //工具栏
    table.on('toolbar(dealDate)', function (obj) {
        var id = obj.config.id;
        var checkStatus = table.checkStatus(id);
        var data = checkStatus.data;
        switch (obj.event) {
            case 'search':
                Refresh()
                break;
            case 'deleteAll':
                var flag = false;
                if (data.length > 0) {
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].dealState == 1) {
                            layer.msg('不能删除已结算的数据!', {icon: 2, time: 1000, shade: [0.5, '#000', true]});
                            flag = true;
                        }
                    }
                    if (!flag) {
                        if (data.length == 1) {
                            layer.confirm('确认删除?', function () {
                                Delete(data, true)
                            })
                        } else {
                            layer.confirm('确认批量删除?', function () {
                                Delete(data, true)
                            })
                        }
                    }
                } else {
                    layer.msg('请选择要从删除的行!', {icon: 0, time: 1000, shade: [0.5, '#000', true]});
                }

                break;
            case 'add':
                var index = layer.open({
                    type: 1,
                    title: '添加交易数据',
                    closeBtn: 1,
                    move: false,
                    content: $("#addContent"),
                    btn: [],
                    area: ['800px', '720px'],
                    end: function () {
                        $("#addform")[0].reset()
                    },
                });
                break;
                form.render();
        }
    })

    //单元行
    table.on('tool(dealDate)', function (obj) { // 双击 toolDouble
        var data = obj.data;
        if (obj.event === 'del') {
            if (data.dealState == 1) {
                layer.msg('不能删除已结算的数据!', {icon: 2, time: 1000, shade: [0.5, '#000', true]});
            } else {
                layer.confirm('确认删除?', function () {
                    Delete(data.dealId, false);
                });
            }
        } else if (obj.event === 'edit') {
            form.val('editform', $.parseJSON(JSON.stringify(data)));

            var index = layer.open({
                type: 1,
                title: '修改交易数据',
                closeBtn: 1,
                move: false,
                area: ['800px', '720px'],
                content: $('#editContent')
            });
        }
    })

    function Delete(MyData, flag) {
        let Arr = [];
        if (!flag) {
            Arr.push(MyData)
        } else {
            for (var i = 0; i < MyData.length; i++) {
                Arr.push(MyData[i].dealId);
            }
        }

        $.post("./deleteDealDate", {myArr: JSON.stringify(Arr)}, function () {
            if (Arr.length <= 1) {
                layer.msg('删除成功!', {icon: 1, time: 1000, shade: [0.5, '#000', true]});
            } else {
                layer.msg('批量删除成功!', {icon: 1, time: 1000, shade: [0.5, '#000', true]});
            }
            Refresh();
        })
    }


    function Refresh() {
        var dealTime = $("#dealTimes").val()
        var securityName = $("#securityName").val()
        table.reload('dealDate', {
            method: 'post'
            , where: {		//请求带的参数，json格式
                dealTime: dealTime,
                securityName: securityName,
            }
            , page: {		//分页参数
                curr: 1		//搜素后从第一页开始展示
            }
        });
        $("#dealTimes").val(dealTime)
        $("#securityName").val(securityName)
        laydate.render({
            elem: '.start', //指定元素
            done: function (value, date, enddate) {
                Sum(false)
                Sum(true)
            }
        });
    }

    //新增提交
    form.on('submit(addsubmit)', function (data) {
        var formData = $('#addform').serialize();
        $.post("./addDealDate", formData, function (msg) {
            if (msg == "1") {
                table.reload('dealDate');
                layer.closeAll();
                layer.msg('添加成功', {icon: 1, time: 1000, shade: [0.5, '#000', true]})
            } else {
                layer.msg('添加失败', {icon: 2, time: 1000, shade: [0.5, '#000', true]})
            }
            laydate.render({
                elem: '.start', //指定元素\
                done: function (value, date, enddate) {
                    Sum(false)
                    Sum(true)

                }
            });

        })
        return false;
    })


    //修改提交
    form.on('submit(editsubmit)', function (data) {
        var formData = $('#editform').serialize();
        $.post("/updateDealDate", formData, function (msg) {
            layer.msg('修改成功', {icon: 1, time: 1000, shade: [0.5, '#000', true]});
            table.reload('dealDate');
            layer.closeAll();
            laydate.render({
                elem: '.start' //指定元素
            });
        });
        return false;
    })

    $(document).ready(function () {
        $(":button[name='offSubmit']").click(function () {
            $("#addform")[0].reset()
            layer.closeAll()
        })
    })
});

layui.use(['layer',
    $ = layui.$,
])

function Sum(flag) {
    var T = (flag ? "" : "1")
    layui.use(['layer'], function () {
        var lixi = 0;
        var dealWay = $("#dealWay" + T).val()
        var dealPrice = $("#dealPrice" + T).val();
        var dealNumber = $("#dealNumber" + T).val();
        var sum = dealPrice * dealNumber;
        var money=$("#money"+T).val()
        var transferFee = $("#transferFee" + T).val()
        var stampDuty = $("#stampDuty" + T).val()
        var control = $("#control" + T).val()
        var handle = $("#handle" + T).val()
        var out = Number(money) + Number(transferFee) + Number(stampDuty) + Number(control) + Number(handle)
        var count = (sum * money) / 100;
        money = count.toFixed(2)
        if (dealPrice != "" && dealPrice != null && dealNumber != "" && dealNumber != null) {
            $.post("./selectBondd", {securityId: $("#securityId" + T).val()}, function (msg) {
                if (msg != null && msg != "") {
                    lixi = (msg.delayDate / 365 * msg.faceAmount * dealNumber * 1).toFixed(2);
                    var dealTime = $("#dealTime" + T).val()
                    var endTime = $("#endTime" + T).val()
                    var day = getDaysBetween(dealTime, endTime);
                    lixi = day * lixi;
                } else {
                    lixi = "";
                }
                if (lixi != "") {
                    $("#securityInterest" + T).val(lixi.toFixed(2))
                } else {
                    $("#securityInterest" + T).val(0)
                }

                if (dealWay == 1) {
                    var sum1 = (Number(sum) + Number(money) / 100 + Number(out) + Number(lixi)).toFixed(2)
                    $("#endMoney" + T).val(sum1)

                } else if (dealWay == 2) {
                    var w = Number(sum) - ((Number(money) / 100 + Number(out) + Number(lixi))).toFixed(2);
                    $("#endMoney" + T).val(w)
                }
            })
            $("#commissionFees" + T).val(money)
            $("#dealMoney" + T).val(sum)
        } else {
            $("#commissionFees" + T).val("")
            $("#dealMoney" + T).val("");
            $("#endMoney" + T).val("")
            $("#securityInterest" + T).val("")
        }
    })
}

/**
 * 计算两个日期之间的天数
 *  date1  开始日期 yyyy-MM-dd
 *  date2  结束日期 yyyy-MM-dd
 *  如果日期相同 返回一天 开始日期大于结束日期，返回0
 */
function getDaysBetween(date1, date2) {
    var startDate = Date.parse(date1);
    var endDate = Date.parse(date2);
    if (startDate > endDate) {
        return 0;
    }
    if (startDate == endDate) {
        return 1;
    }
    var days = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000);
    return days;
}

